//
//  TableViewController.swift
//  ToDoList
//
//  Created by Qingke on 16/4/11.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit



class TableViewController: UITableViewController {
var tasks = [Task]()
    var catgegoryItem : CategoryClass!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let task1 = Task(name: "task1", isChecked: true)
        let task2 = Task(name: "task2", isChecked: true)
        tasks += [task1, task2]
        navigationItem.title = catgegoryItem.name
        print(catgegoryItem.name)
        
        //print(dataFildPath())

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return tasks.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! MyCell

        // Configure the cell...  cell是默认重用的。cell加载很占用资源。 这里的 讲mycell作为一个 类，可以自定义，cell的组件，设置目标
        let task = tasks[indexPath.row]
        let isfinished = cell.isFinashed as UILabel!

        
        cell.customLabel.text = task.name
        if task.isChecked {
            isfinished.text = "√"
        } else {
            cell.isFinashed.text = "X"
        }

        return cell
    }
    //代理方法进行处理。
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let task = tasks[indexPath.row]
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            let label1 = cell.viewWithTag(1) as! UILabel
            if label1.text == "√" {
                label1.text = "x"
                task.isChecked = false
            } else {
                label1.text = "√"
                task.isChecked = true
            }
                
            
           
        }
    }
    //MARK: func by myself
   
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let navC = segue.destinationViewController as! UINavigationController
        let targetController = navC.topViewController as! addItemTableViewController
        targetController.addItemFunc1 = self

        if segue.identifier == "edit" {
            let cell = sender as! UITableViewCell
            if let indexPath = tableView.indexPathForCell(cell) {
                let retask = tasks [ indexPath.row ]
                targetController.retask = retask
                targetController.indexOftask = indexPath
            }
        } else  if segue.identifier == "addItem"{
                    }
    }
    
    func dataFildPath () -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentationDirectory, .UserDomainMask, true)
        let filePath = paths[0] as NSString
        return filePath.stringByAppendingPathComponent("TaskList.plist")
    }
    
    func saveTaskList() {
        // 创建对象
        let data = NSMutableData()  //Mutable表明可改变的
        // 把数据写入到data对象
        
        let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(tasks, forKey: "TaskList")
        archiver.finishEncoding()
        // 把对象写入文件
        
        data.writeToFile(dataFildPath(), atomically: true)
        
    }
    
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    

    
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tasks.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension TableViewController : addItemdelegate {
    func addItemFunc(controller: addItemTableViewController, didFinishAdd task: Task) {
        let IndexPath = NSIndexPath(forRow: tasks.count, inSection: 0)
        tasks.append(task)
        tableView.insertRowsAtIndexPaths([IndexPath], withRowAnimation: .None)
    }
    func addItemFunc (controller: addItemTableViewController ,didFinishedit task :Task, indePathOfCell indexPath: NSIndexPath ){
        tasks[indexPath.row] = task
        // 方法1 tableView.reloadData()
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        // 方法3 不是很懂
    }
}
